<template>
  <div class="sales-return-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <div class="header-left">
        <h2>订单退货管理</h2>
        <p>管理销售订单的退货申请、审核和处理</p>
        </div>
        <div class="header-right">
        <el-button type="primary" @click="handleAddDialogShow(); showAddDialog = true">
          <i class="el-icon-plus"></i> 新增退货订单
        </el-button>
        <el-button type="success" @click="refreshData">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="退货单号">
          <el-input v-model="searchForm.returnNo" placeholder="请输入退货单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="待审核" :value="1"></el-option>
            <el-option label="审核通过" :value="2"></el-option>
            <el-option label="已完成" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%">
        <el-table-column prop="returnNo" label="退货单号" width="150" fixed="left">
          <template #default="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">{{ scope.row.returnNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="原订单号" width="150"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>
        <el-table-column prop="totalReturnAmount" label="退货金额" width="120">
          <template #default="scope">
            <span class="amount-display">¥{{ scope.row.totalReturnAmount?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="returnReason" label="退货原因" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="returnDate" label="退货日期" width="120"></el-table-column>
        <el-table-column prop="creatorName" label="创建人" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetail(scope.row)">详情</el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              size="small" 
              type="success" 
              @click="submitForAudit(scope.row)">提交审核</el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              size="small" 
              type="warning" 
              @click="openAuditDialog(scope.row)">审核</el-button>
            <el-button 
              v-if="scope.row.status === 2" 
              size="small" 
              type="success" 
              @click="completeReturn(scope.row)">完成</el-button>
            <el-button 
              v-if="canEdit(scope.row)" 
              size="small" 
              type="info" 
              @click="editReturn(scope.row)">编辑</el-button>
            <el-button 
              v-if="canDelete(scope.row)" 
              size="small" 
              type="danger" 
              @click="deleteReturn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>

    <!-- 新增退货订单对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="新增退货订单"
      width="90%"
      :close-on-click-modal="false"
      @close="resetReturnForm">
      <el-form
        ref="returnFormRef"
        :model="returnForm"
        :rules="returnFormRules"
        label-width="120px">
        
        <!-- 基本信息 -->
        <div class="form-section">
          <h4>基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="退货单号">
                <el-input v-model="returnForm.returnNo" placeholder="系统自动生成" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称">
                <el-input v-model="returnForm.customerName" placeholder="选择原订单后自动填充" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="退货原因" prop="returnReason">
                <el-select v-model="returnForm.returnReason" placeholder="请选择退货原因" style="width: 100%">
                  <el-option label="商品质量问题" value="商品质量问题"></el-option>
                  <el-option label="商品损坏" value="商品损坏"></el-option>
                  <el-option label="尺寸不合适" value="尺寸不合适"></el-option>
                  <el-option label="颜色不符" value="颜色不符"></el-option>
                  <el-option label="功能缺陷" value="功能缺陷"></el-option>
                  <el-option label="包装破损" value="包装破损"></el-option>
                  <el-option label="客户取消订单" value="客户取消订单"></el-option>
                  <el-option label="其他原因" value="其他原因"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="原订单号" prop="orderId">
                <el-input
                  v-model="returnForm.orderId"
                  placeholder="请输入订单ID"
                  style="width: 100%"
                  @blur="handleOrderIdInput">
                  <template #append>
                    <el-button @click="searchOrderById">查询</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="退货日期" prop="returnDate">
                <el-date-picker
                  v-model="returnForm.returnDate"
                  type="date"
                  placeholder="请选择退货日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注">
                <el-input v-model="returnForm.remark" placeholder="请输入备注信息"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 退货商品列表 -->
        <div class="form-section">
          <div class="section-header">
            <h4>退货商品</h4>
            <el-button type="primary" size="small" @click="addReturnItem">添加商品</el-button>
          </div>
          
          <el-table :data="returnForm.items" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称" width="200">
              <template #default="scope">
                <el-input
                  v-model="scope.row.productName"
                  placeholder="请选择商品"
                  readonly
                  @click="openProductDialog(scope.$index)">
                  <template #append>
                    <el-button @click="openProductDialog(scope.$index)">选择</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="skuCode" label="SKU编码" width="150"></el-table-column>
            <el-table-column prop="originalQuantity" label="原订单数量" width="120"></el-table-column>
            <el-table-column prop="returnQuantity" label="退货数量" width="120">
              <template #default="scope">
                  <el-input-number 
                  v-model="scope.row.returnQuantity"
                  :min="1"
                  :max="scope.row.originalQuantity || 999999"
                  size="small"
                  @change="calculateItemAmount(scope.$index)">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="returnPrice" label="退货单价" width="120">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.returnPrice"
                    :min="0" 
                  :precision="2"
                    size="small"
                  @change="calculateItemAmount(scope.$index)">
                  </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="returnAmount" label="退货金额" width="120">
              <template #default="scope">
                ¥{{ (scope.row.returnQuantity * scope.row.returnPrice).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="退货原因" width="150">
              <template #default="scope">
                <el-select v-model="scope.row.reason" placeholder="选择原因" size="small" style="width: 100%">
                  <el-option label="质量问题" value="质量问题"></el-option>
                  <el-option label="损坏" value="损坏"></el-option>
                  <el-option label="尺寸不合适" value="尺寸不合适"></el-option>
                  <el-option label="颜色不符" value="颜色不符"></el-option>
                  <el-option label="功能缺陷" value="功能缺陷"></el-option>
                  <el-option label="包装破损" value="包装破损"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeReturnItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="form-summary">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="总退货金额">
                <span class="total-amount">¥{{ totalReturnAmount.toFixed(2) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReturnForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="退货订单详情"
      width="80%">
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退货单号">{{ currentDetail.returnNo }}</el-descriptions-item>
          <el-descriptions-item label="原订单号">{{ currentDetail.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentDetail.customerName }}</el-descriptions-item>
          <el-descriptions-item label="退货日期">{{ currentDetail.returnDate }}</el-descriptions-item>
          <el-descriptions-item label="退货原因">{{ currentDetail.returnReason }}</el-descriptions-item>
          <el-descriptions-item label="总退货金额">¥{{ currentDetail.totalReturnAmount?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 退货商品详情 -->
        <div class="detail-items">
          <h4>退货商品</h4>
          <el-table :data="currentDetail.items" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="skuCode" label="SKU编码"></el-table-column>
            <el-table-column prop="returnQuantity" label="退货数量"></el-table-column>
            <el-table-column prop="returnPrice" label="退货单价"></el-table-column>
            <el-table-column prop="returnAmount" label="退货金额"></el-table-column>
            <el-table-column prop="reason" label="退货原因"></el-table-column>
          </el-table>
        </div>

        <!-- 审核记录 -->
        <div v-if="currentDetail.auditRecords && currentDetail.auditRecords.length > 0" class="detail-audit">
          <h4>审核记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="audit in currentDetail.auditRecords"
              :key="audit.id"
              :timestamp="audit.auditTime"
              :type="audit.auditResult === 1 ? 'success' : 'danger'">
              <p>审核人：{{ audit.auditorName }}</p>
              <p>审核结果：{{ audit.auditResult === 1 ? '通过' : '拒绝' }}</p>
              <p>审核意见：{{ audit.auditOpinion }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 商品选择对话框 -->
    <el-dialog
      v-model="showProductDialog"
      title="选择商品"
      width="70%"
      :close-on-click-modal="false">
      <div class="product-search">
        <el-input
          v-model="productSearchKeyword"
          placeholder="请输入商品名称或SKU编码搜索"
          style="width: 300px; margin-bottom: 20px;"
          @input="searchProducts">
          <template #append>
            <el-button @click="searchProducts">搜索</el-button>
          </template>
        </el-input>
      </div>
      
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @row-click="selectProduct">
        <el-table-column prop="product_name" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="spu_code" label="SPU编码" width="150"></el-table-column>
        <el-table-column prop="retail_price" label="零售价" width="100">
          <template #default="scope">
            ¥{{ scope.row.retail_price?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="scope">
            {{ scope.row.stock || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="primary" @click="selectProduct(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showProductDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="showAuditDialog"
      title="审核退货订单"
      width="500px">
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditFormRules"
        label-width="100px">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="0">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditOpinion">
          <el-input
            v-model="auditForm.auditOpinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见">
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAuditDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { salesReturnApi } from '@/api/salesReturn'
import { orderApi } from '@/api/order'
import { productApi } from '@/api/product'
import { getCurrentUser } from '@/utils/api'


// 响应式数据
const loading = ref(false)
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const showAuditDialog = ref(false)
const isEdit = ref(false)
const orderSearchLoading = ref(false)
const orderOptions = ref([])
const showProductDialog = ref(false)
const productSearchKeyword = ref('')
const productOptions = ref([])
const currentEditItemIndex = ref(-1)

// 搜索表单
const searchForm = reactive({
  returnNo: '',
  customerName: '',
  status: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 退货表单
const returnForm = reactive({
  id: null,
  returnNo: '',
  orderId: null,
  customerId: null,
  customerName: '',
  returnDate: '',
  returnReason: '',
  remark: '',
  items: []
})

// 退货表单验证规则
const returnFormRules = {
  orderId: [{ required: true, message: '请选择原订单', trigger: 'change' }],
  returnDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }],
  returnReason: [{ required: true, message: '请选择退货原因', trigger: 'change' }],
  items: [
    {
      type: 'array',
      required: true,
      message: '请至少添加一个退货商品',
      trigger: 'change'
    },
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一个退货商品'))
          return
        }
        
        for (let i = 0; i < value.length; i++) {
          const item = value[i]
          if (!item.productName) {
            callback(new Error(`第${i + 1}行商品名称不能为空`))
            return
          }
          if (!item.returnQuantity || item.returnQuantity <= 0) {
            callback(new Error(`第${i + 1}行退货数量必须大于0`))
            return
          }
          if (!item.returnPrice || item.returnPrice <= 0) {
            callback(new Error(`第${i + 1}行退货单价必须大于0`))
            return
          }
        }
        callback()
      },
      trigger: 'change'
    }
  ]
}

// 审核表单
const auditForm = reactive({
  id: null,
  auditResult: 1,
  auditOpinion: ''
})

// 审核表单验证规则
const auditFormRules = {
  auditResult: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  auditOpinion: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
}

// 当前详情数据
const currentDetail = ref(null)

// 表单引用
const returnFormRef = ref()
const auditFormRef = ref()

// 计算属性
const totalReturnAmount = computed(() => {
  return returnForm.items.reduce((sum, item) => {
    return sum + (item.returnQuantity * item.returnPrice)
  }, 0)
})

// 方法
const refreshData = () => {
  loadTableData()
}

const loadTableData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startTime = searchForm.dateRange[0] + 'T00:00:00'
      params.endTime = searchForm.dateRange[1] + 'T23:59:59'
    }
    
    const response = await salesReturnApi.getReturnOrderPage(params)
    console.log('=== API Response Debug ===')
    console.log('Full Response:', response)
    console.log('Response Type:', typeof response)
    console.log('Response Keys:', Object.keys(response || {}))
    
    // 尝试多种数据格式解析
    let records = []
    let total = 0
    
    if (response) {
      // 情况1: 标准格式 {success: true, data: {records: [], total: 0}}
      if (response.success && response.data) {
        console.log('Format 1: Standard format with success flag')
        const pageData = response.data
        if (pageData.records) {
          records = pageData.records
          total = pageData.total || pageData.size || records.length
        }
      }
      // 情况2: 直接分页格式 {records: [], total: 0}
      else if (response.records) {
        console.log('Format 2: Direct pagination format')
        records = response.records
        total = response.total || response.size || records.length
      }
      // 情况3: 直接数组格式 [...]
      else if (Array.isArray(response)) {
        console.log('Format 3: Direct array format')
        records = response
        total = records.length
      }
      // 情况4: MyBatis-Plus IPage格式 {current: 1, pages: 1, records: [], size: 20, total: 0}
      else if (response.current !== undefined && response.records) {
        console.log('Format 4: MyBatis-Plus IPage format')
        records = response.records
        total = response.total || records.length
      }
    }
    
    console.log('Parsed Records:', records)
    console.log('Parsed Total:', total)
    
    tableData.value = records
    pagination.total = total
    
    if (records.length === 0) {
      console.warn('No data found to display')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNum = 1
  loadTableData()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    returnNo: '',
    customerName: '',
    status: '',
    dateRange: []
  })
  pagination.pageNum = 1
  loadTableData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  loadTableData()
}

const handleCurrentChange = (page) => {
  pagination.pageNum = page
  loadTableData()
}

const getStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'success'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '审核通过',
    3: '已完成'
  }
  return statusMap[status] || '未知'
}

const searchOrders = async (query) => {
  if (query) {
    orderSearchLoading.value = true
    try {
      const response = await orderApi.searchOrders({ keyword: query })
      if (response.success) {
        orderOptions.value = response.data || []
      } else {
        ElMessage.error(response.message || '搜索订单失败')
        orderOptions.value = []
      }
    } catch (error) {
      console.error('搜索订单失败:', error)
      ElMessage.error('搜索订单失败')
      orderOptions.value = []
    } finally {
      orderSearchLoading.value = false
    }
  }
}

const handleOrderChange = async (orderId) => {
  if (!orderId) {
    returnForm.customerId = null
    returnForm.customerName = ''
    returnForm.items = []
    return
  }

  try {
    console.log('开始查询订单ID:', orderId)
    
    // 根据订单ID查询客户名称
    const response = await orderApi.getCustomerNameByOrderId(orderId)
    console.log('客户查询响应:', response)
    
    if (response && response.success) {
      returnForm.customerName = response.data
      console.log('设置客户名称:', response.data)
      // 加载订单商品
      loadOrderItems(orderId)
    } else {
      const errorMsg = (response && response.message) || '查询客户信息失败'
      console.error('客户查询失败:', errorMsg)
      ElMessage.error(errorMsg)
      returnForm.customerName = ''
    }
  } catch (error) {
    console.error('查询客户信息失败:', error)
    ElMessage.error('查询客户信息失败')
    returnForm.customerName = ''
  }
}

const handleOrderIdInput = () => {
  const orderId = returnForm.orderId
  if (orderId && /^\d+$/.test(orderId)) {
    handleOrderChange(parseInt(orderId))
  }
}

const searchOrderById = () => {
  const orderId = returnForm.orderId
  if (orderId && /^\d+$/.test(orderId)) {
    handleOrderChange(parseInt(orderId))
  } else {
    ElMessage.warning('请输入有效的订单ID')
  }
}

const loadOrderItems = async (orderId) => {
  try {
    console.log('开始加载订单商品，订单ID:', orderId)
    
    const response = await orderApi.getOrderDetail(orderId)
    console.log('订单详情响应:', response)
    
    if (response && response.success) {
      const items = response.data.items || []
      console.log('订单商品列表:', items)
      
      returnForm.items = items.map(item => {
        // 确保数值类型正确
        const qty = parseFloat(item.qty) || 1
        const price = parseFloat(item.price) || 0
        const productId = parseInt(item.productId) || null
        const skuId = item.skuId ? (isNaN(item.skuId) ? item.skuId : parseInt(item.skuId)) : null
        
        const mappedItem = {
          orderItemId: item.id,
          productId: productId,
          productName: item.productName || '',
          skuId: skuId,
          skuCode: item.skuCode || '',
          originalQuantity: Math.max(qty, 1),
          returnQuantity: Math.max(qty, 1),
          returnPrice: price,
          returnAmount: (qty * price).toFixed(2),
          reason: ''
        }
        console.log('映射后的商品项:', mappedItem)
        return mappedItem
      })
      
      console.log('最终退货商品列表:', returnForm.items)
    } else {
      const errorMsg = (response && response.message) || '加载订单商品失败'
      console.error('加载订单商品失败:', errorMsg)
      ElMessage.error(errorMsg)
      returnForm.items = []
    }
  } catch (error) {
    console.error('加载订单商品失败:', error)
    ElMessage.error('加载订单商品失败')
    returnForm.items = []
  }
}

const addReturnItem = () => {
  returnForm.items.push({
    orderItemId: null,
    productId: null,
    productName: '',
    skuId: null,
    skuCode: '',
    originalQuantity: 1,
    returnQuantity: 1,
    returnPrice: 0,
    returnAmount: 0,
    reason: ''
  })
}

const removeReturnItem = (index) => {
  returnForm.items.splice(index, 1)
}

const calculateItemAmount = (index) => {
  if (index >= 0 && index < returnForm.items.length) {
    const item = returnForm.items[index]
    item.returnAmount = (item.returnQuantity * item.returnPrice).toFixed(2)
  }
}

const openProductDialog = (index) => {
  // 记录当前编辑的行索引
  currentEditItemIndex.value = index
  showProductDialog.value = true
  searchProducts()
}

const searchProducts = async () => {
  try {
    const params = {
      pageNo: 1,
      pageSize: 20,
      keyword: productSearchKeyword.value
    }
    
    const response = await productApi.getProductPage(params)
    if (response.success) {
      productOptions.value = response.data.records || []
    } else {
      ElMessage.error(response.message || '搜索商品失败')
      productOptions.value = []
    }
  } catch (error) {
    console.error('搜索商品失败:', error)
    ElMessage.error('搜索商品失败')
    productOptions.value = []
  }
}

const selectProduct = (product) => {
  if (currentEditItemIndex.value >= 0 && currentEditItemIndex.value < returnForm.items.length) {
    const item = returnForm.items[currentEditItemIndex.value]
    item.productId = product.id
    item.productName = product.product_name
    item.skuId = null // 暂时设为null，因为这是SPU级别的选择
    item.skuCode = product.spu_code // 使用SPU编码作为SKU编码
    item.returnPrice = product.retail_price || product.purchase_price || 0
    item.returnQuantity = 1
    item.originalQuantity = Math.max(product.stock || 1, 1)
    item.returnAmount = (item.returnQuantity * item.returnPrice).toFixed(2)
  }
  showProductDialog.value = false
}

const submitReturnForm = async () => {
  try {
    await returnFormRef.value.validate()
    
    console.log('提交退货订单数据:', returnForm)
    
    // 处理日期格式，将 YYYY-MM-DD 转换为 YYYY-MM-DDTHH:mm:ss
    const currentUser = getCurrentUser()
    const processedData = {
      ...returnForm,
      totalReturnAmount: totalReturnAmount.value,
      creatorId: 1  // 使用默认用户ID，或者从localStorage获取用户ID
    }
    
    // 如果退货日期存在，转换为完整的日期时间格式
    if (processedData.returnDate) {
      processedData.returnDate = `${processedData.returnDate}T00:00:00`
    }
    
    console.log('处理后的数据:', processedData)
    
    let response
    if (isEdit.value) {
      response = await salesReturnApi.updateReturnOrder(processedData)
    } else {
      response = await salesReturnApi.addReturnOrder(processedData)
    }
    
    console.log('API响应:', response)
    
    if (response && response.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      showAddDialog.value = false
      loadTableData()
      resetReturnForm()
    } else {
      const errorMsg = (response && response.message) || '操作失败'
      console.error('操作失败:', errorMsg)
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

const resetReturnForm = () => {
  Object.assign(returnForm, {
    id: null,
    returnNo: '',
    orderId: null,
    customerId: null,
    customerName: '',
    returnDate: '',
    returnReason: '',
    remark: '',
    items: []
  })
  isEdit.value = false
  if (returnFormRef.value) {
    returnFormRef.value.resetFields()
  }
}

const viewDetail = async (row) => {
  try {
    const response = await salesReturnApi.getReturnOrderDetail(row.id)
    if (response.success) {
      currentDetail.value = response.data
      showDetailDialog.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const editReturn = (row) => {
  isEdit.value = true
  Object.assign(returnForm, {
    id: row.id,
    returnNo: row.returnNo,
    orderId: row.orderId,
    customerId: row.customerId,
    customerName: row.customerName,
    returnDate: row.returnDate,
    returnReason: row.returnReason,
    remark: row.remark,
    items: row.items || []
  })
  showAddDialog.value = true
}

const deleteReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个退货订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await salesReturnApi.deleteReturnOrder(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const submitForAudit = async (row) => {
  try {
    await ElMessageBox.confirm('确定要提交审核吗？提交后将无法编辑', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await salesReturnApi.submitForAudit(row.id)
    if (response.success) {
      ElMessage.success('提交审核成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '提交审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交审核失败:', error)
      ElMessage.error('提交审核失败')
    }
  }
}

const openAuditDialog = (row) => {
  auditForm.id = row.id
  auditForm.auditResult = 1
  auditForm.auditOpinion = ''
  showAuditDialog.value = true
}

const submitAudit = async () => {
  try {
    await auditFormRef.value.validate()
    
    const response = await salesReturnApi.auditReturnOrder(
      auditForm.id,
      auditForm.auditResult,
      auditForm.auditOpinion,
      1 // 当前用户ID，这里需要从用户状态获取
    )
    
    if (response.success) {
      ElMessage.success('审核成功')
      showAuditDialog.value = false
      loadTableData()
    } else {
      ElMessage.error(response.message || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  }
}

const completeReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要完成这个退货订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await salesReturnApi.completeReturnOrder(row.id)
    if (response.success) {
      ElMessage.success('完成成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '完成失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成失败:', error)
      ElMessage.error('完成失败')
    }
  }
}

const canEdit = (row) => {
  return row.status === 0 // 只有草稿状态可以编辑
}

const canDelete = (row) => {
  return row.status === 0 // 只有草稿状态可以删除
}

// 监听新增对话框显示状态
const handleAddDialogShow = async () => {
  if (!isEdit.value) {
    // 新增时自动生成退货单号
    try {
      const response = await salesReturnApi.generateReturnNo()
      if (response.success) {
        returnForm.returnNo = response.data
      } else {
        ElMessage.error(response.message || '生成退货单号失败')
        // 如果API失败，使用本地生成作为备选方案
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        const day = String(now.getDate()).padStart(2, '0')
        const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
        returnForm.returnNo = `TH${year}${month}${day}${random}`
      }
    } catch (error) {
      console.error('生成退货单号失败:', error)
      ElMessage.error('生成退货单号失败')
      // API调用失败时的备选方案
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      returnForm.returnNo = `TH${year}${month}${day}${random}`
    }
  }
}

// 生命周期
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
/* 全局容器 */
.sales-return-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h1 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form .el-form-item {
  margin-bottom: 16px;
  margin-right: 24px;
}

.search-form .el-input,
.search-form .el-select {
  width: 200px;
}

.search-form .el-date-editor {
  width: 280px;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-section .el-table th {
  background: #fafafa;
  color: #333;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #e8e8e8;
}

.table-section .el-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
  font-size: 14px;
}

.table-section .el-table tr:hover {
  background: #f9f9f9;
}

/* 金额显示 */
.amount-display {
  font-weight: 600;
  color: #52c41a;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 状态标签 */
.el-tag {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  font-size: 14px;
  padding: 8px 16px;
}

.el-button:hover {
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 分页区域 */
.pagination-section {
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #e8e8e8;
}

/* 表单区域 */
.form-section {
  margin-bottom: 24px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.form-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.add-item-section {
  margin-top: 16px;
  text-align: center;
}

.summary-section {
  background: white;
  border: 1px solid #d9d9d9;
}

.summary-value {
  font-weight: 600;
  color: #333;
}

.total-amount {
  color: #52c41a;
  font-size: 16px;
}

.status-draft {
  color: #666;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
  padding: 16px 0 0 0;
  border-top: 1px solid #e8e8e8;
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sales-return-container {
    padding: 16px;
  }
  
  .page-header {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-right {
    margin-top: 16px;
  }
  
  .search-section {
    padding: 16px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 16px;
    margin-right: 0;
  }
  
  .search-form .el-input,
  .search-form .el-select,
  .search-form .el-date-editor {
    width: 100%;
  }
  
  .form-section {
    padding: 16px;
  }
  
  .pagination-section {
    padding: 16px;
  }
}
</style>
